// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import FastClick from 'fastclick'
import VueRouter from 'vue-router'
import { WechatPlugin, ToastPlugin, LoadingPlugin, ConfirmPlugin, AlertPlugin } from 'vux'
import VueResource from 'vue-resource'
import global from './util/global'
import toast from './util/toast'
import App from './App'
import Home from './components/home'
import Product from './components/product'
import Subscribe from './components/subscribe'
import User from './components/user'
import Sample from './components/sample'
import Contact from './components/contact'
import SampleDetail from './components/sample-detail'

Vue.use(VueRouter)

const routes = [{
  name: 'home',
  path: '/',
  component: Home
}, {
  name: 'home',
  path: '/home',
  component: Home
}, {
  name: 'product',
  path: '/product',
  component: Product
}, {
  name: 'subscribe',
  path: '/subscribe',
  component: Subscribe
}, {
  name: 'user',
  path: '/user',
  component: User
}, {
  name: 'sample',
  path: '/sample',
  component: Sample
}, {
  name: 'contact',
  path: '/contact',
  component: Contact
}, {
  name: 'sample-detail',
  path: '/sample-detail',
  component: SampleDetail
}]

const router = new VueRouter({
  routes
})

FastClick.attach(document.body)
Vue.config.productionTip = false
Vue.use(VueResource)
Vue.use(WechatPlugin)
Vue.use(ToastPlugin)
Vue.use(LoadingPlugin)
Vue.use(VueRouter)
Vue.use(ConfirmPlugin)
Vue.use(AlertPlugin)
Vue.prototype.global = global
Vue.prototype.toast = toast
Vue.use(require('vue-wechat-title'))

Vue.http.interceptors.push((request, next) => {
  Vue.$vux.loading.show({
    text: '加载中'
  })
  if (request.url.indexOf('https://open.weixin.qq.com') === -1) {
    request.url = 'http://' + process.env.hosturl + request.url
  }
  let timeout = setTimeout(() => {
    next(request.respondWith(request.body, {
      status: 408,
      statusText: '请求超时'
    }))
  }, 20000)
  next(response => {
    clearTimeout(timeout)
    Vue.$vux.loading.hide()
    if (response.body.code === 200) {
      return response
    } else if (response.body.code === 400) {
      Vue.$vux.alert.show({
        content: response.body.desc,
        onHide () {
          window.location.href = 'http://' + window.location.host + window.location.pathname
        }
      })
    } else {
      Vue.$vux.toast.show({
        type: 'text',
        text: response.body.desc,
        position: 'middle',
        width: '18em'
      })
    }
  })
})

/* eslint-disable no-new */
new Vue({
  router,
  render: h => h(App)
}).$mount('#app-box')
